//
//  MNDManagerAccountViewController.m
//  minidai
//
//  Created by Vitas on 2018/5/28.
//  Copyright © 2018年 迷你金服. All rights reserved.
//

#import "MNDManagerAccountViewController.h"
#import "MNDSwitchAccountCell.h"
#import "MNDAddAccountCell.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "MNDLoginViewController.h"
#import "MNDSwitchAccountViewController.h"

#define kMNDSwitchAccountCell @"MNDSwitchAccountCell"
#define kMNDAddAccountCell @"MNDAddAccountCell"

@interface MNDManagerAccountViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation MNDManagerAccountViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"账号管理";
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.tableView.tableFooterView = [UIView new];
    NSArray *array = [UserDefaultsTool objectForKey:kAccountUserNameArray];
    
    MNDLoginUserModel *loginUser = [MNDLoginUserModel currentLoginUser];
    //老版本保存用户信息
    if (!array || array.count == 0) {
        NSDictionary *userDict = @{
                                    @"user_name": self.user.userName,
                                    @"user_phone":self.user.userPhone,
                                    @"user_photo":self.user.userPhoto
                                              };
        array = @[userDict];
        [UserDefaultsTool saveObject:array forKey:kAccountUserNameArray];
    }
    NSMutableArray *tempArray = [NSMutableArray arrayWithArray:array];
    
    NSDictionary *currentUserDict = [NSDictionary dictionary];
    //取到当前登录的用户
    for (NSDictionary *dict in array) {
        if ([dict[@"user_name"] isEqualToString:loginUser.user_name]) {
            currentUserDict = dict;
            [tempArray removeObject:dict];
        }
    }
    [tempArray insertObject:currentUserDict atIndex:0];
    [UserDefaultsTool saveObject:[tempArray copy] forKey:kAccountUserNameArray];
    [self.dataArray addObjectsFromArray:tempArray];
    [self.tableView reloadData];
    [self initialBarbuttonItems];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popAction:) name:@"AddAccountPopToroot" object:nil];
    // Do any additional setup after loading the view.
}

- (void)popAction:(NSNotification *)notification {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)initialBarbuttonItems {
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"编辑"
                                                             style:UIBarButtonItemStylePlain
                                                            target:self
                                                            action:@selector(editAction:)];
    [item setTitleTextAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Regular" size:14.0]} forState:UIControlStateNormal];
    [item setTintColor:kColorBlack];
    
    if (@available(iOS 11.0, *)) {
        self.navigationItem.rightBarButtonItem = item;
    } else {
        self.navigationItem.rightBarButtonItems = @[spaceItem, item];
    }
    if (self.dataArray.count == 1) {
        self.navigationItem.rightBarButtonItem = nil;
    }
}

- (void)editAction:(UIBarButtonItem *)sender {
    if ([sender.title isEqualToString:@"编辑"]) {
        sender.title = @"完成";
        [self.tableView setEditing:YES animated:YES];
    }else{
        sender.title = @"编辑";
        [self.tableView setEditing:NO animated:YES];
    }
    
    
    
    //    [self performSegueWithIdentifier:[MNDSettingViewController description] sender:nil];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count+1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    __weak __typeof(self)weakSelf = self;
    if (indexPath.row == self.dataArray.count) {
        MNDAddAccountCell *cell = [tableView dequeueReusableCellWithIdentifier:kMNDAddAccountCell];
        [cell.addBtn bk_addEventHandler:^(id sender) {//添加账号
            [weakSelf addAccountAction];
        } forControlEvents:UIControlEventTouchUpInside];
        return cell;
        
    }else {
        MNDSwitchAccountCell *cell = [tableView dequeueReusableCellWithIdentifier:kMNDSwitchAccountCell];
        if (indexPath.row == 0) {
            cell.tipButton.hidden = NO;
        }else{
            cell.tipButton.hidden = YES;
        }
        NSDictionary *dict = self.dataArray[indexPath.row];
        NSString *userName = dict[@"user_name"];
        cell.accountLabel.text = userName;
        NSString *phoneStr = dict[@"user_phone"];
        if (phoneStr.length == 11) {
            phoneStr = [phoneStr stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
        }
        cell.phoneLabel.text = phoneStr;
//        [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:dict[@"user_photo"]]];
        [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:dict[@"user_photo"]] placeholderImage:[UIImage imageNamed:@"user_center_avatar_color"]];
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

//侧滑
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    __weak __typeof(self)weakSelf = self;
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        [weakSelf deleteAccountAction:indexPath.row];
    }];
    
    return @[deleteRowAction];
    
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0 || indexPath.row == self.dataArray.count ) {
        return NO;
    }
    return YES;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0 ) {
        return;
    }
    if (indexPath.row == self.dataArray.count) {
        [self addAccountAction];
        return;
    }
    
    NSDictionary *dict = self.dataArray[indexPath.row];
    MNDSwitchAccountViewController *loginVC = [UIStoryboard viewControllerWithIdentifier:@"MNDSwitchAccountViewController"];
    loginVC.phoneStr = dict[@"user_phone"];
    loginVC.iconImageStr = dict[@"user_photo"];
    [self.navigationController pushViewController:loginVC animated:YES];
}
- (void)deleteAccountAction:(NSInteger)index {
    if (_dataArray && _dataArray.count > 0) {
        [self.dataArray removeObjectAtIndex:index];
        NSArray *array = [UserDefaultsTool objectForKey:kAccountUserNameArray];
        NSMutableArray *arrayM = [NSMutableArray arrayWithArray:array];
        [arrayM removeObjectAtIndex:index];
        [UserDefaultsTool saveObject:arrayM forKey:kAccountUserNameArray];
        if (self.dataArray.count == 1) {
            self.navigationItem.rightBarButtonItem = nil;
        }
        [self.tableView reloadData];
    }
}

- (void)addAccountAction {
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
//    UINavigationController *naviVC = [storyboard instantiateInitialViewController];
    MNDLoginViewController *loginVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDLoginViewController"];
    UINavigationController *naviVC = [[UINavigationController alloc] initWithRootViewController:loginVC];
    loginVC.isAddAccount = YES;
    [self presentViewController:naviVC animated:YES completion:^{
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
